'use strict';

/////////////////////////////////////////////////
/////////////////////////////////////////////////
// BANKIST APP

// Data
const account1 = {
  owner: 'Jonas Schmedtmann',
  movements: [200, 450, -400, 3000, -650, -130, 70, 1300],
  interestRate: 1.2, // %
  pin: 1111,
  locale: 'pt-PT',
  currency: 'EUR',
};

const account2 = {
  owner: 'Jessica Davis',
  movements: [5000, 3400, -150, -790, -3210, -1000, 8500, -30],
  interestRate: 1.5,
  pin: 2222,
  locale: 'en-US',
  currency: 'USD',
};

const account3 = {
  owner: 'Steven Thomas Williams',
  movements: [200, -200, 340, -300, -20, 50, 400, -460],
  interestRate: 0.7,
  pin: 3333,
  locale: 'en-GB',
  currency: 'GBP',
};

const account4 = {
  owner: 'Sarah Smith',
  movements: [430, 1000, 700, 50, 90],
  interestRate: 1,
  pin: 4444,
  locale: 'cn-CN',
  currency: 'CNY',
};

const accounts = [account1, account2, account3, account4];

// Elements
const labelWelcome = document.querySelector('.welcome');
const labelDate = document.querySelector('.date');
const labelBalance = document.querySelector('.balance__value');
const labelSumIn = document.querySelector('.summary__value--in');
const labelSumOut = document.querySelector('.summary__value--out');
const labelSumInterest = document.querySelector('.summary__value--interest');
const labelTimer = document.querySelector('.timer');

const containerApp = document.querySelector('.app');
const containerMovements = document.querySelector('.movements');

const btnLogin = document.querySelector('.login__btn');
const btnTransfer = document.querySelector('.form__btn--transfer');
const btnLoan = document.querySelector('.form__btn--loan');
const btnClose = document.querySelector('.form__btn--close');
const btnSort = document.querySelector('.btn--sort');

const inputLoginUsername = document.querySelector('.login__input--user');
const inputLoginPin = document.querySelector('.login__input--pin');
const inputTransferTo = document.querySelector('.form__input--to');
const inputTransferAmount = document.querySelector('.form__input--amount');
const inputLoanAmount = document.querySelector('.form__input--loan-amount');
const inputCloseUsername = document.querySelector('.form__input--user');
const inputClosePin = document.querySelector('.form__input--pin');

/////////////////////////////////////////////////
/////////////////////////////////////////////////
// LECTURES

const currencies = new Map([
  ['USD', 'United States dollar'],
  ['EUR', 'Euro'],
  ['GBP', 'Pound sterling'],
]);

const movements = [200, 450, -400, 3000, -650, -130, 70, 1300];

/////////////////////////////////////////////////
function formatCur(value, locale, currency) {
  return new Intl.NumberFormat(locale, {
    style: 'currency',
    currency: currency,
  }).format(value);
}

function displayMovements(acc, sort = false) {
  containerMovements.innerHTML = '';
  const m = sort ? acc.movements.slice().sort((a, b) => a - b) : acc.movements;

  m.forEach(function (value, i) {
    const type = value > 0 ? 'deposit' : 'withdrawal';
    const now = new Date();
    const displayDate = new Intl.DateTimeFormat(currentAcount.locale).format(
      now
    );
    const formattedValue = formatCur(value, acc.locale, acc.currency);
    const html = `
    <div class="movements__row">
      <div class="movements__type movements__type--${type}">${
      i + 1
    } ${type}</div>
    <div class="movements__date">${displayDate}</div>
      <div class="movements__value">${formattedValue}</div>
    </div>`;

    containerMovements.insertAdjacentHTML('afterbegin', html);
  });
}

function displayBalance(acc) {
  const balance = acc.movements.reduce((i, j) => i + j, 0);
  acc.balance = balance;
  labelBalance.textContent = formatCur(balance, acc.locale, acc.currency);
}

function calDisplaySummary(acc) {
  const incomes = acc.movements.filter(i => i > 0).reduce((i, j) => i + j, 0);
  labelSumIn.textContent = formatCur(incomes, acc.locale, acc.currency);

  const outcomes = acc.movements.filter(i => i < 0).reduce((i, j) => i + j, 0);
  labelSumOut.textContent = formatCur(
    Math.abs(outcomes),
    acc.locale,
    acc.currency
  );
  const interest = acc.movements
    .filter(i => i > 0)
    .map(i => (i * acc.interestRate) / 100)
    .filter(i => i >= 1)
    .reduce((acc, cur) => acc + cur, 0);
  labelSumInterest.textContent = formatCur(interest, acc.locale, acc.currency);
}

function updateUI(acc) {
  displayMovements(acc);
  displayBalance(acc);
  calDisplaySummary(acc);
}
// timer
function startLogOutTimer() {
  let time = 600;
  const timer = setInterval(function () {
    const min = String(Math.trunc(time / 60)).padStart(2, 0);
    const sec = String(time % 60).padStart(2, 0);
    labelTimer.textContent = `${min}:${sec}`;
    time--;
    if (time === 0) {
      clearInterval(timer);
      containerApp.style.opacity = '0';
      labelWelcome.textContent = 'Log in to get started';
    }
  }, 1000);
  return timer;
}
let currentAcount, timer;
btnLogin.addEventListener('click', function (e) {
  e.preventDefault();
  currentAcount = accounts.find(i => i.owner === inputLoginUsername.value);
  // console.log(currentAcount);
  if (currentAcount?.pin === Number(inputLoginPin.value)) {
    // movements
    labelWelcome.textContent = `Welcome back, ${
      currentAcount.owner.split(' ')[0]
    }`;
    containerApp.style.opacity = '1';
    const now = new Date();
    const exact = {
      hour: 'numeric',
      minute: 'numeric',
      day: 'numeric',
      month: 'long',
      year: 'numeric',
      weekday: 'long',
    };
    labelDate.textContent = new Intl.DateTimeFormat(
      currentAcount.locale,
      exact
    ).format(now);
    updateUI(currentAcount);

    // clear input fields
    inputLoginUsername.value = inputLoginPin.value = '';
    if (timer) clearInterval(timer);
    timer = startLogOutTimer();
  }
});

btnTransfer.addEventListener('click', function (e) {
  e.preventDefault();
  const amount = Number(Math.floor(inputTransferAmount.value));
  const recieverAcc = accounts.find(i => i.owner === inputTransferTo.value);

  if (
    amount > 0 &&
    recieverAcc &&
    currentAcount.balance >= amount &&
    recieverAcc.owner !== currentAcount.owner
  ) {
    currentAcount.movements.push(-amount);
    recieverAcc.movements.push(amount);
    inputTransferAmount.value = inputTransferTo.value = '';
    updateUI(currentAcount);
    clearInterval(timer);
    timer = startLogOutTimer();
  }
});

btnLoan.addEventListener('click', function (e) {
  e.preventDefault();
  const amount = Number(inputLoanAmount.value);
  if (amount > 0 && currentAcount.movements.some(i => i >= amount / 10)) {
  }
  currentAcount.movements.push(Math.floor(amount));
  updateUI(currentAcount);
  inputLoanAmount.value = '';
  clearInterval(timer);
  timer = startLogOutTimer();
});

btnClose.addEventListener('click', function (e) {
  e.preventDefault();
  if (
    inputCloseUsername.value === currentAcount.owner &&
    Number(inputClosePin.value) === currentAcount.pin
  ) {
    const index = accounts.find(i => i.owner === currentAcount.owner);

    accounts.splice(index, 1);

    containerApp.style.opacity = 0;
  }
  inputCloseUsername.value = inputClosePin.value = '';
});

let sorted = false;
btnSort.addEventListener('click', function (e) {
  e.preventDefault();
  displayMovements(currentAcount, !sorted);
  sorted = !sorted;
});
// setInterval(function () {
//   console.log(new Date());
// }, 1000);
/*
const data1 = [5, 2, 4, 1, 15, 8, 3];
const data2 = [16, 6, 10, 5, 6, 1, 4];

function calAverageHumanAge(age) {
  const humanAge = age.map(i => (i <= 2 ? i * 2 : i * 4 + 16));
  const adulst = humanAge.filter(i => i >= 18);
  console.log(adulst);
  let sum = 0;
  adulst.forEach(i => {
    sum += i;
  });
  const ave = sum / adulst.length;
  return `average: ${ave}`;
}

console.log(calAverageHumanAge(data1));
console.log(calAverageHumanAge(data2));
*/

/*
function calAverageHumanAge(age) {
  return age
    .map(i => (i <= 2 ? i * 2 : i * 4 + 16))
    .filter(i => i >= 18)
    .reduce((acc, cur, index, array) => acc + cur / array.length, 0);
}
const av1 = calAverageHumanAge([5, 2, 4, 1, 15, 8, 3]);
const av2 = calAverageHumanAge([16, 6, 10, 5, 6, 1, 4]);
console.log(av1, av2);
*/

/*
const dogs = [
  { weight: 22, curFood: 250, owners: ['Alice', 'Bob'] },
  { weight: 8, curFood: 200, owners: ['Matilda'] },
  { weight: 13, curFood: 275, owners: ['Sarah', 'John'] },
  { weight: 32, curFood: 340, owners: ['Michael'] },
];

dogs.forEach(i => (i.recFood = parseInt(i.weight ** 0.75 * 28)));

function calcAppetite(owner) {
  const dogOf = dogs.find(i => i.owners.includes(owner));
  if (dogOf.curFood > dogOf.weight ** 0.75 * 28) {
    console.log(`It's eating too much!`);
  } else if (dogOf.curFood === dogOf.weight ** 0.75 * 28) {
    console.log(`It's exactly ideal appetite`);
  } else {
    console.log(`It's eating too little!`);
  }
}
calcAppetite('Sarah');

const ownersEatTooMuch = dogs
  .filter(i => i.recFood < i.curFood)
  .flatMap(i => i.owners);
console.log(ownersEatTooMuch);
const ownersEatTooLittle = dogs
  .filter(i => i.recFood > i.curFood)
  .flatMap(i => i.owners);
console.log(ownersEatTooLittle);
console.log(
  `${ownersEatTooMuch}'s dogs eat too much! and ${ownersEatTooLittle}'s dogs eat too little!`
);
console.log(dogs.some(i => i.recFood === i.curFood));
console.log(dogs.some(i => i.recFood >= i.curFood));
*/
